import DetailContainer, { Title } from "@/components/DetailContainer";
import { get_core_list } from "@/services/controller_core";
import { get_device_list } from "@/services/device";
import { add_modules, edit_modules, get_modules_detail } from "@/services/modules";
import { get_topic_list } from "@/services/topic";
import type { ProFormInstance } from "@ant-design/pro-components";
import {
  ProCard,
  ProForm,
  ProFormGroup,
  ProFormList,
  ProFormSelect,
  ProFormText,
  ProFormTextArea
} from "@ant-design/pro-components";
import { history, useParams } from "@umijs/max";
import { useSetState } from "ahooks";
import { Form, message } from "antd";
import { useEffect, useRef } from "react";

const modulesMap = {
  add: add_modules,
  update: edit_modules
};

const UseAddEdit = () => {
  const [form] = Form.useForm();
  const { id } = useParams();
  const isNew = id === "new";
  const formRef = useRef<ProFormInstance<any>>();
  const [state, setState] = useSetState<any>({
    core_list: [],
    device_list: [],
    topic_list: [],
    task_delete_id: [],
    old_task_data: []
  });

  // 获取核心
  const get_core_listFun = async () => {
    let params = {
      page: 1,
      page_size: 10
    };
    let resp = await get_core_list(params);
    if (resp.code === 0) {
      setState({
        core_list: resp.data.list
      });
    }
  };

  // 获取设备
  const get_device_listFun = async () => {
    let params = {
      page: 1,
      page_size: 10
    };
    let resp = await get_device_list(params);
    if (resp.code === 0) {
      setState({
        device_list: resp.data.list
      });
    }
  };
  // 获取Topic
  const get_topic_listFun = async () => {
    let params = {
      page: 1,
      page_size: 10
    };
    let resp = await get_topic_list(params);
    if (resp.code === 0) {
      setState({
        topic_list: resp.data.list
      });
    }
  };
  useEffect(() => {
    get_core_listFun();
    get_device_listFun();
    get_topic_listFun();
  }, []);

  // 格式化数据
  const setTasklist = (data: any) => {
    const result = data.reduce((acc: any, obj: any) => {
      const core = obj.core;
      if (!acc[core]) {
        acc[core] = [];
      }
      acc[core].push(obj);
      return acc;
    }, {});

    let task_lists = [];
    // eslint-disable-next-line guard-for-in
    for (let key in result) {
      let obj = {
        core: Number(key),
        task_list_detail: result[key]
      };
      task_lists.unshift(obj);
    }
    return task_lists;
  };

  const setTaskAdd = (data: any) => {
    let new_arr = [];
    for (let i = 0; i < data.length; i++) {
      for (let t = 0; t < data[i].task_list_detail.length; t++) {
        if (t > 500) {
          console.log("防止 死循环 =>");
          return;
        }
        let new_data1 = data[i].task_list_detail[t];
        new_data1.core = data[i].core;
        new_arr.push(new_data1);
      }
    }
    return new_arr;
  };

  // 合并所有的task 列表
  const mergeTaskList = (data: any) => {
    let new_arr: any = [];
    data.forEach((item: any) => {
      let el = item.task_list_detail;
      el = el.map((item3: any) => {
        if (!item3.core) {
          item3.core = item.core;
          return item3;
        } else {
          return item3;
        }
      });
      new_arr = new_arr.concat(el);
    });
    return new_arr;
  };

  // 分解 task-add delete edit
  const mergeTaskListFormat = (data: any) => {
    let new_arr = mergeTaskList(data);
    console.log("old_arr =>", state.old_task_data);
    console.log("new_arr =>", new_arr);

    let task_add = new_arr.filter((item: any) => !item.id);
    console.log("task_add =>", task_add);

    let task_edit = new_arr.filter((item: any) => item.id);
    console.log("task_edit =>", task_edit);

    let task_delete = state.old_task_data.filter(
      (item: any) => !task_edit.some((obj: any) => obj.id === item.id)
    );
    if (task_delete.length > 0) {
      task_delete = task_delete.map((item: any) => item.id);
    }
    return {
      task_add,
      task_edit,
      task_delete
    };
  };

  return (
    <DetailContainer>
      <ProForm
        form={form}
        formRef={formRef}
        layout="vertical"
        grid={true}
        rowProps={{
          gutter: [24, 0]
        }}
        request={async () => {
          if (isNew) return {};
          let resp = await get_modules_detail(id as string);
          if (resp.code === 0) {
            let task_list_new = setTasklist(resp.data.task_list);
            console.log("task_list_new =>", task_list_new);
            setState({
              old_task_data: mergeTaskList(task_list_new)
            });
            return {
              ...resp.data.modules_detail,
              task_list: task_list_new
            };
          } else {
            return {};
          }
        }}
        onFinish={async () => {
          const values = form.getFieldsValue(true);
          let params: any = {};
          if (!isNew) {
            let modules_detail: any = {
              id: Number(id),
              name: values.name,
              modules_img: values.modules_img,
              remark: values.remark
            };
            let new_params = {
              modules_detail,
              ...mergeTaskListFormat(values.task_list)
            };
            params = new_params;
          } else {
            params = {
              name: values.name,
              modules_img: values.modules_img,
              remark: values.remark,
              task_list: setTaskAdd(values.task_list)
            };
          }
          const resp = await modulesMap[isNew ? "add" : "update"](params);
          if (resp?.code === 0) {
            history.push("/modules/list");
            message.success(`${isNew ? "新增" : "编辑"}成功`);
          }
        }}
      >
        {/* Modules info */}
        <div style={{ width: "100%" }}>
          <Title>Modules Info</Title>
        </div>
        <ProFormText
          label="Modules name"
          rules={[{ required: true, message: "此项必填" }]}
          name="name"
          colProps={{
            span: 12
          }}
        />

        <ProFormText
          label="Modules Img"
          name="modules_img"
          colProps={{
            span: 24
          }}
        />

        <ProFormTextArea label="remark" placeholder="" name="remark" />

        {/* Modules core */}
        <div style={{ width: "100%" }}>
          <Title>Modules Task</Title>
        </div>

        <ProFormList
          name="task_list"
          label=""
          min={1}
          copyIconProps={false}
          itemRender={({ listDom, action }, { record }) => {
            return (
              <ProCard
                bordered
                extra={action}
                title={record?.name}
                style={{
                  marginBlockEnd: 8
                }}
              >
                {listDom}
              </ProCard>
            );
          }}
        >
          <ProFormSelect
            label="Core List"
            rules={[{ required: true, message: "此项必填" }]}
            name="core"
            fieldProps={{
              fieldNames: {
                label: "name",
                value: "id"
              }
            }}
            colProps={{
              span: 12
            }}
            options={state.core_list}
          />

          <ProFormList name="task_list_detail" label="" copyIconProps={false}>
            <ProFormGroup key="group">
              <ProFormText
                name="task_name"
                label="Task Name"
                rules={[{ required: true, message: "此项必填" }]}
                colProps={{
                  span: 5
                }}
              />
              <ProFormText
                name="gpio"
                label="GPIO"
                rules={[{ required: true, message: "此项必填" }]}
                colProps={{
                  span: 3
                }}
              />
              <ProFormSelect
                label="Device"
                rules={[{ required: true, message: "此项必填" }]}
                name="device"
                fieldProps={{
                  fieldNames: {
                    label: "name",
                    value: "id"
                  }
                }}
                colProps={{
                  span: 8
                }}
                options={state.device_list}
              />

              <ProFormSelect
                label="Topic"
                rules={[{ required: true, message: "此项必填" }]}
                name="topic"
                fieldProps={{
                  fieldNames: {
                    label: "name",
                    value: "id"
                  }
                }}
                colProps={{
                  span: 8
                }}
                options={state.topic_list}
              />
            </ProFormGroup>
          </ProFormList>
        </ProFormList>
      </ProForm>
    </DetailContainer>
  );
};

export default UseAddEdit;
